#ifndef __STORAGE_H__
#define __STORAGE_H__

#include <Arduino.h>
#include <EEPROM.h>

// Some code taken from here: http://forum.arduino.cc/index.php/topic,41497.0.html

class StorageStream {
    friend class Storage;

protected:
    int position;

private:
    void reset();
};

class StorageOutput : public StorageStream {
public:
    template<class T>
    int write(const T &value) {
        int i;
        const byte *p = (const byte *) (const void *) &value;
        for (i = 0; i < sizeof(value); i++) {
            EEPROM.write(position++, *p++);
        }
        return i;
    }
};

class StorageInput : public StorageStream {
public:
    template<class T>
    int read(T &value) {
        int i;
        byte *p = (byte *) (void *) &value;
        for (i = 0; i < sizeof(value); i++) {
            *p++ = EEPROM.read(position++);
        }
        return i;
    }
};

class Persistent {
public:
    virtual void load(StorageInput &in) = 0;

    virtual void store(StorageOutput &out) = 0;
};

class Storage {
private:
    StorageInput in;
    StorageOutput out;

public:
    void load(int cnt, Persistent *);

    void save(int cnt, Persistent *);
};

#endif